﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

namespace mamnontuoitho7.AppCode
{
    public class Upload : IHttpHandler, IRequiresSessionState
    {
        private Album _album = new Album();
        private ThumbnailClass _thumb = new ThumbnailClass();
        private ImageAlbum _imageAlbum = new ImageAlbum();

        public Upload()
        {
        }

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            // Example of using a passed in value in the query string to set a categoryId
            // Now you can do anything you need to witht the file.
            string  _productID = "";
            if (!string.IsNullOrEmpty(context.Request.QueryString["ProductID"]))
            {
                _productID = context.Request.QueryString["ProductID"];
            }
            


            // get the applications path

            string uploadPath = context.Server.MapPath(context.Request.ApplicationPath + "images/album/album-" + _productID + "/photo/");
            
            // loop through all the uploaded files
            for (int j = 0; j < context.Request.Files.Count; j++)
            {
                // get the current file
                HttpPostedFile uploadFile = context.Request.Files[j];
                // if there was a file uploded
                if (uploadFile.ContentLength > 0)
                {
                    string fullUploadPath = Path.Combine(uploadPath, uploadFile.FileName);
                    uploadFile.SaveAs(fullUploadPath);

                    ImageMedia img = ImageMedia.Create(File.ReadAllBytes(fullUploadPath));

                    if (File.Exists(fullUploadPath))
                        File.Delete(fullUploadPath);  
                     

                    string ext = Path.GetExtension(uploadFile.FileName).ToLower().Trim();
                    Guid guid = System.Guid.NewGuid();
                    string name = guid.ToString();
                    string filename = _productID + "-" + name + ext;

                    _imageAlbum.ImageInsert(_productID, filename);// tạo record


                    filename = filename.Length > 70 ? filename.Substring(0, 70) : filename;
                    // string FilePath = Request.PhysicalApplicationPath + "images/album/album-" + _productID + "/photo/" + filename;
                    string FilePath = context.Request.PhysicalApplicationPath + "images/album/album-" + _productID + "/photo/" + filename;

                    

                    float imgWidth = img.Width;
                    float imgHeight = img.Height;

                    //////// tạo hình lớn trong thu muc photo; thu nhỏ lại nếu wa lớn với 1canh là 600
                    int size = 600;
                    float imgSize1 = imgHeight < imgWidth ? imgHeight : imgWidth;
                    //the approximately pixel size of thumbnail image is 150 x 150 based on ratio             
                    float imgResize1 = imgSize1 <= size ? (float)1.0 : size / imgSize1;

                    float imgWidth1 = imgWidth * imgResize1;
                    float imgHeight1 = imgHeight * imgResize1;
                      

                    img.Resize((int)imgWidth1, (int)imgHeight1);
                    File.WriteAllBytes(FilePath, img.ToByteArray());

                    //generating the thumbnail  
                    //// hình nhỏ trong thư mục photo/thumbnail; height luôn là 106
                    int height = 106;
                    float imgResize2 = imgHeight <= height ? (float)1.0 : height / imgHeight;
                    float width = imgWidth * imgResize2;

                    string FilePath2 = context.Request.PhysicalApplicationPath + "images/album/album-" + _productID + "/photo/thumbnail/" + filename;

                    img.Resize((int)width, (int)height);
                    File.WriteAllBytes(FilePath2, img.ToByteArray());



                    // save the file to the upload directory

                    //use this if testing from a classic style upload, ie. 

                    // <form action="Upload.axd" method="post" enctype="multipart/form-data">
                    //    <input type="file" name="fileUpload" />
                    //    <input type="submit" value="Upload" />
                    //</form>

                    // this is because flash sends just the filename, where the above 
                    //will send the file path, ie. c:\My Pictures\test1.jpg
                    //you can use Test.thm to test this page.
                    //string filename = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf("\\"));
                    //uploadFile.SaveAs(string.Format("{0}{1}{2}", tempFile, "Upload\\", filename));

                    // use this if using flash to upload
                   // uploadFile.SaveAs(Path.Combine(uploadPath, uploadFile.FileName));

                    // HttpPostedFile has an InputStream also.  You can pass this to 
                    // a function, or business logic. You can save it a database:

                    //byte[] fileData = new byte[uploadFile.ContentLength];
                    //uploadFile.InputStream.Write(fileData, 0, fileData.Length);
                    // save byte array into database.

                    // something I do is extract files from a zip file by passing
                    // the inputStream to a function that uses SharpZipLib found here:
                    // http://www.icsharpcode.net/OpenSource/SharpZipLib/
                    // and then save the files to disk.                    
                }
            }

            // Used as a fix for a bug in mac flash player that makes the 
            // onComplete event not fire
            HttpContext.Current.Response.Write(" ");
        }

        #endregion

    }


}